import React, { useEffect, useState, useMemo } from 'react';
import { Text, View, device, getLaunchOptionsSync,onDeviceInfoUpdated } from '@ray-js/ray';
import { NavBar, Battery, Icon } from '@ray-js/smart-ui';
import clsx from 'clsx';
import SmartSwitch from '@/components/SmartSwitch';
import { useActions, useProps, useDevice } from '@ray-js/panel-sdk';
import debounce from 'lodash/debounce';
import Strings from '@/i18n';
import * as Raw from '@/utils/raw';
import styles from './index.module.less';

export function Home() {
  const { getDeviceInfo, registerDeviceListListener, onDeviceOnlineStatusUpdate } = device;
  const power = useProps(props => props.switch); // 开关
  const battery = useProps(props => props.battery_percentage); // 电量
  const timer = useProps(props => props.timer); // 定时
  const work = useProps(props => props.work); // 工作状态
  const [deviceInfo, setDeviceInfo] = useState<any>({});
  const isOnline = deviceInfo?.isOnline as boolean; // 是否在线
  const network = useDevice(device => device.network.isConnected);
  const bluetooth = useDevice(device => device.bluetooth.available);
  const isConnected = isOnline && network && bluetooth; // 是否连接
  // 定时状态
  const [timing, setTiming] = useState({
    isOn: 0, // 0: 关闭 1: 开启
    hour: 0, // 定时小时数1-24 0: 常开
  });
  const [working, setWorking] = useState({
    gear: 0, // 档位 0: 未开启 1: 低档 2:中档 3:高档
    start: 0, // 开始
    pause: 0, // {Strings.getLang('pause')}
  });
  const [lowSwitch, setLowSwitch] = useState(false);
  const [middleSwitch, setMiddleSwitch] = useState(false);
  const [highSwitch, setHighSwitch] = useState(false);

  const actions = useActions();

  useEffect(() => {
    const {
      query: { deviceId },
    } = getLaunchOptionsSync();

    getDeviceInfo({
      deviceId,
      success: info => {
        console.log('getDeviceInfo success', info);
        setDeviceInfo(info);
      },
    });
    registerDeviceListListener({ deviceIdList: [deviceId] });
    onDeviceOnlineStatusUpdate(env => {
      getDeviceInfo({
        deviceId,
        success: info => {
          console.log('getDeviceInfo success', info);
          setDeviceInfo(info);
        },
      });
    });

    onDeviceInfoUpdated(_ => {
      getDeviceInfo({
        deviceId,
        success: info => {
          setDeviceInfo(info);
        },
      });
    });
  }, []);

  useEffect(() => {
    if (timer) {
      console.log('定时:', timer);
      const { isOn, hour } = Raw.parseTimingRaw(timer);
      setTiming({ isOn, hour });
    }
    if (work) {
      console.log('工作状态:', work);
      const { gear, start, pause } = Raw.parseWorkRaw(work);
      setWorking({ gear, start, pause });
      setLowSwitch(gear === 1);
      setMiddleSwitch(gear === 2);
      setHighSwitch(gear === 3);
    }
  }, [timer, work]);

  const handlePower = (value: boolean) => {
    actions.switch.set(value);
  };

  const handleWork = useMemo(
    () =>
      debounce((gear: number, start: number, pause: number) => {
        actions.work.set(Raw.generateWorkRaw(gear, start, pause));
      }, 500),
    []
  );

  const handleTimer = useMemo(
    () =>
      debounce((isOn: number, hour: number) => {
        actions.timer.set(Raw.generateTimingRaw(isOn, hour));
      }, 500),
    []
  );
  return (
    <>
      <NavBar
        title={deviceInfo.name}
        leftTextType="home"
        border={false}
        customStyle={{ backgroundColor: '#EFF3FB' }}
      />
      <View className={styles.view}>
        <View className={styles.content}>
          <View className={styles.header}>
            <Battery size={15} value={battery} type="horizontal" />
            <View className={styles.statusWarp}>
              <View
                className={clsx(styles.statusPanel, {
                  [styles.statusPanelDisable]: !isConnected,
                })}
              >
                <View className={styles.statusBox}>
                  <View className={styles.statusBoxItem}>
                    {isConnected ? (
                      <Icon name={require('@/res/icons/wifi.svg')} size={90} />
                    ) : (
                      <Icon name={require('@/res/icons/wifi_disabled.svg')} size={90} />
                    )}
                    <Text
                      style={{
                        fontSize: 28,
                        color: deviceInfo?.isOnline ? '#767676' : '#767676',
                      }}
                    >
                      {isConnected ? Strings.getLang('connected') : Strings.getLang('disconnected')}
                    </Text>
                  </View>
                </View>
              </View>
            </View>
          </View>
          <View
            className={clsx(styles.wrap, {
              [styles.disabled]: !isConnected || !power,
            })}
          >
            <View className={styles.card}>
              <View className={styles.cell}>
                <View style={{ flex: 1 }}>
                  <Text className={styles.title}>{Strings.getLang('low')}</Text>
                </View>
                <View style={{ flex: 3 }}>
                  <Text>{Strings.getLang('start')}&nbsp;15S</Text>
                  <Text>-----</Text>
                  <Text>{Strings.getLang('pause')}&nbsp;200S</Text>
                </View>
                <SmartSwitch
                  value={lowSwitch}
                  onChange={(value: boolean) => {
                    setLowSwitch(value);
                    if (value) {
                      setMiddleSwitch(false);
                      setHighSwitch(false);
                    } else if (!middleSwitch && !highSwitch) {
                      setLowSwitch(true);
                      return;
                    }
                    handleWork(value ? 1 : 0, 15, 200);
                  }}
                />
              </View>
            </View>
            <View className={styles.card}>
              <View className={styles.cell}>
                <View style={{ flex: 1 }}>
                  <Text className={styles.title}>{Strings.getLang('middle')}</Text>
                </View>
                <View style={{ flex: 3 }}>
                  <Text>{Strings.getLang('start')}&nbsp;15S</Text>
                  <Text>-----</Text>
                  <Text>{Strings.getLang('pause')}&nbsp;100S</Text>
                </View>
                <SmartSwitch
                  value={middleSwitch}
                  onChange={(value: boolean) => {
                    setMiddleSwitch(value);
                    if (value) {
                      setLowSwitch(false);
                      setHighSwitch(false);
                    } else if (!lowSwitch && !highSwitch) {
                      setMiddleSwitch(true);
                      return;
                    }
                    handleWork(value ? 2 : 0, 15, 100);
                  }}
                />
              </View>
            </View>
            <View className={styles.card}>
              <View className={styles.cell}>
                <View style={{ flex: 1 }}>
                  <Text className={styles.title}>{Strings.getLang('high')}</Text>
                </View>
                <View style={{ flex: 3 }}>
                  <Text>{Strings.getLang('start')}&nbsp;15S</Text>
                  <Text>-----</Text>
                  <Text>{Strings.getLang('pause')}&nbsp;60S</Text>
                </View>
                <SmartSwitch
                  value={highSwitch}
                  onChange={(value: boolean) => {
                    setHighSwitch(value);
                    if (value) {
                      setLowSwitch(false);
                      setMiddleSwitch(false);
                    } else if (!lowSwitch && !middleSwitch) {
                      setHighSwitch(true);
                      return;
                    }
                    handleWork(value ? 3 : 0, 15, 60);
                  }}
                />
              </View>
            </View>
            <View
              className={clsx(styles.card, {
                [styles.disabled]: !isConnected || !power,
              })}
            >
              <View className={styles.timerWrap}>
                <Text className={styles.title}>{Strings.getLang('smartTiming')}</Text>
                <View className={styles.timerBoxWrap}>
                  <View
                    className={clsx(styles.timerBox, {
                      [styles.timerBoxAction]: timing.isOn === 1 && timing.hour === 1,
                    })}
                    onClick={() => {
                      const isOn = timing.isOn === 1 && timing.hour === 1 ? 0 : 1;
                      handleTimer(isOn, 1);
                      setTiming({ isOn, hour: 1 });
                    }}
                  >
                    <Text>1H</Text>
                  </View>
                  <View
                    className={clsx(styles.timerBox, {
                      [styles.timerBoxAction]: timing.isOn === 1 && timing.hour === 4,
                    })}
                    onClick={() => {
                      const isOn = timing.isOn === 1 && timing.hour === 4 ? 0 : 1;
                      setTiming({ isOn, hour: 4 });
                      handleTimer(isOn, 4);
                    }}
                  >
                    <Text>4H</Text>
                  </View>
                  <View
                    className={clsx(styles.timerBox, {
                      [styles.timerBoxAction]: timing.isOn === 1 && timing.hour === 8,
                    })}
                    onClick={() => {
                      const isOn = timing.isOn === 1 && timing.hour === 8 ? 0 : 1;
                      setTiming({ isOn, hour: 8 });
                      handleTimer(isOn, 8);
                    }}
                  >
                    <Text>8H</Text>
                  </View>
                  <View
                    className={clsx(styles.timerBox, {
                      [styles.timerBoxAction]: timing.isOn === 1 && timing.hour === 24,
                    })}
                    onClick={() => {
                      const isOn = timing.isOn === 1 && timing.hour === 24 ? 0 : 1;
                      handleTimer(isOn, 24);
                      setTiming({ isOn, hour: 24 });
                    }}
                  >
                    <Text>24H</Text>
                  </View>
                  <View
                    className={clsx(styles.timerBox, {
                      [styles.timerBoxAction]: timing.isOn === 1 && timing.hour === 0,
                    })}
                    onClick={() => {
                      const isOn = timing.isOn === 1 && timing.hour === 0 ? 0 : 1;
                      handleTimer(isOn, 0);
                      setTiming({ isOn, hour: 0 });
                    }}
                  >
                    <Text>{Strings.getLang('alwaysOn')}</Text>
                  </View>
                </View>
              </View>
            </View>
          </View>

          <View
            className={clsx(styles.powerBox, {
              [styles.disabled]: !isConnected,
            })}
            onClick={() => handlePower(!power)}
          >
            <View
              className={clsx(styles.powerOn, {
                [styles.powerOff]: !power,
              })}
            >
              <Icon name={require('@/res/icons/power.svg')} color="red" size={30} />
            </View>
          </View>
        </View>
      </View>
    </>
  );
}

export default Home;
